const express = require('express');
const router = express.Router();
const mysql = require('mysql');
const bcrypt = require('bcrypt');
const constant = require('../data/constant');
const auth = require('../middleware/auth');
const multer = require('multer');


let upload = multer({
    limits:{
        //限制文件大小500Mb
        fileSize: 500*1000*1000,
        //限制文件数量
        files: 1
    },
    storage: multer.diskStorage({
        destination: function (req, file, cb) {
            cb(null, './uploads/');
        },
        filename: function (req, file, cb) {
            const fileFormat = (file.originalname).split('.') // 取后缀
            var changedName = (new Date().getTime())+'-'+file.originalname;
            cb(null, changedName);
        }
    })
});
 
//单个文件上传
let singleUpload = upload.single('file');
router.post('/single',auth, (req, res) => {
    singleUpload(req,res,(err)=>{
        if(!!err){
            console.log(err.message)
            res.send({
                res:{
                    ok: 0,
                    status:'error',
                    originalname: '',
                    msg: err.message
                }
            });
            return;
        }
        if(!!req.file){
            // console.log(req.file);
            res.send({
                res:{
                    ok: 1,
                    status:'success',
                    originalname: req.file.originalname,
                    path:req.file.path,
                    size:req.file.size,
                    msg: '资源上传成功！您可以在填写完其他信息后对该资源进行提交审核操作'
                }
            });
        } else {
            res.send({
                res:{
                    ok: 0,
                    status:'error',
                    originalname: '',
                    msg: '没有上传任何文件！'
                }
            })
        }
    });
});

router.post('/file_info_commit',auth, (req, res) => {
    var Pool = mysql.createPool({
        'host':constant.DB_HOST_NAME,
        'user':constant.DB_USER,
        'password':constant.DB_PWD,
        'database':constant.DB_NAME,
        'multipleStatements': true // 支持执行多条 sql 语句
    });
    Pool.getConnection( (err,connection) => {
        if(err){
            console.log(err);
            res.send({
                'res':{
                    'ok': 0,
                    'msg':'数据库连接失败'
                }
            });
        }else{
            // 查找文件夹
            let sql = '';
            let sqlParams = [];
            if(req.body.request_type == 1){
                // 项目
                sql = "INSERT INTO"+ 
                " files(`name`,`originalname`,`size`,`type`,`uploader`,`lastlevel`,`path`,`desc`,`stage`,`course`,`version`,`tags`,`status`,`project`)"+
                " VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?);"
                sqlParams = [
                    req.body.name,
                    req.body.originalname,
                    req.body.size,
                    req.body.type,
                    req.body.uploader,
                    req.body.location,
                    req.body.path,
                    req.body.desc,
                    req.body.stage,
                    req.body.course,
                    req.body.version,
                    req.body.tags,
                    1,
                    parseInt(req.body.project_id)
                ];
            }else{
                // 资产库
                sql = "INSERT INTO"+ 
                " files(`name`,`originalname`,`size`,`type`,`uploader`,`lastlevel`,`path`,`desc`,`stage`,`course`,`version`,`tags`,`location_array`)"+
                " VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?);"
                let location_array = req.body.location_array.join(',');
                sqlParams = [
                    req.body.name,
                    req.body.originalname,
                    req.body.size,
                    req.body.type,
                    req.body.uploader,
                    req.body.location,
                    req.body.path,
                    req.body.desc,
                    req.body.stage,
                    req.body.course,
                    req.body.version,
                    req.body.tags,
                    location_array
                ];
            }
            // console.log(sql,sqlParams);
            connection.query(sql,sqlParams,async (err,data) => {
                if(err){
                    console.log(err);
                    res.statusCode = 500;
                    res.send({
                        'res':{
                            'ok': 0,
                            'msg':'数据库连接失败'
                        }
                    });
                }else{
                    res_data = JSON.stringify(data);//把data对象转为字符串，去掉RowDataPacket
                    res_data = JSON.parse(res_data);//把results字符串转为json对象
                    let  sql = "INSERT INTO"+
                    " history_version(`file_id`,`originalname`,`version`,`uploader`,`update_log`,`path`,`size`)"+
                    " VALUES(?,?,?,?,?,?,?);"
                    var  sqlParams = [
                        res_data.insertId,
                        req.body.originalname,
                        req.body.version,
                        req.body.uploader,
                        req.body.desc,
                        req.body.path,
                        req.body.size
                    ];
                    console.log(sql,sqlParams);
                    //console.log(sqlParams);
                    connection.query(sql,sqlParams,async (err,data) => {
                        if(err){
                            console.log(err);
                            res.statusCode = 500;
                            res.send({
                                'res':{
                                    'ok': 0,
                                    'msg':'数据库连接失败'
                                }
                            });
                        }else{
                            res_data_inner = JSON.stringify(data);//把data对象转为字符串，去掉RowDataPacket
                            res_data_inner = JSON.parse(res_data_inner);//把results字符串转为json对象
                            //console.log(res_data,res_data_inner);
                            if(res_data.affectedRows === 1 && res_data_inner.affectedRows === 1){
                                res.send({
                                    res:{
                                        ok:1,
                                        msg:"提交成功！您上传的资源正在等待管理员审核，审核结果可以在'我的——个人中心——消息中心'中找到"
                                    }
                                });
                            }else{
                                res.send({
                                    res:{
                                        ok:0,
                                        msg:"提交失败，请稍后再试！"
                                    }
                                })
                            }
                        }
                    })
                }
            });
            connection.release();
        }
    });
});

// 资源版本更新的接口
router.post('/file_update',auth, (req, res) => {
    var Pool = mysql.createPool({
        'host':constant.DB_HOST_NAME,
        'user':constant.DB_USER,
        'password':constant.DB_PWD,
        'database':constant.DB_NAME,
        'multipleStatements': true // 支持执行多条 sql 语句
    });
    Pool.getConnection( (err,connection) => {
        if(err){
            console.log(err);
            res.send({
                'res':{
                    'ok': 0,
                    'msg':'数据库连接失败'
                }
            });
        }else{
            // 构造sql语句
            let  sql = "UPDATE files SET path = ?,originalname = ?,version = ? WHERE file_id = ?;"+
            "INSERT INTO"+
            " history_version(`file_id`,`originalname`,`version`,`uploader`,`update_log`,`path`,`size`)"+
            " VALUES(?,?,?,?,?,?,?);"
            var  sqlParams = [
                req.body.path,
                req.body.originalname,
                parseFloat(req.body.version),
                req.body.file_id,
                req.body.file_id,
                req.body.originalname,
                req.body.version,
                req.body.uploader,
                req.body.desc,
                req.body.path,
                req.body.size
            ];
            connection.query(sql,sqlParams,async (err,data) => {
                if(err){
                    console.log(err);
                    res.statusCode = 500;
                    res.send({
                        'res':{
                            'ok': 0,
                            'msg':'数据库连接失败'
                        }
                    });
                }else{
                    res_data = JSON.stringify(data);//把data对象转为字符串，去掉RowDataPacket
                    res_data = JSON.parse(res_data);//把results字符串转为json对象
                    console.log(res_data);
                    if(res_data[0].affectedRows === 1 && res_data[1].affectedRows === 1){
                        res.send({
                            res:{
                                ok:1,
                                msg:"提交成功！您更新的资源正在等待管理员审核，审核结果可以在'我的——个人中心——消息中心'中找到"
                            }
                        });
                    }else{
                        res.send({
                            res:{
                                ok:0,
                                msg:"提交失败，请稍后再试！"
                            }
                        })
                    }
                }
            });
            connection.release();
        }
    });
});

module.exports = router;